﻿using System.ComponentModel;
using System.Reflection;

Dictionary<string, string> q = new Dictionary<string, string>
        {
    { "Id", "1" },
            { "Age", "30" },
            { "Name", "张三" },
            { "Sex", "男" }
        };
ToEntity(typeof(Yuan), q);

object ToEntity(Type _type, Dictionary<string, string> enty)
{
    try
    {
        var obj = Activator.CreateInstance(_type);
        var entity = _type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var property in entity)
        {
            //if (enty.ContainsKey(property.Name))
            //{
            //    var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
            //    var value = Convert.ChangeType(enty[property.Name], property.PropertyType);
            //    property.SetValue(obj, value);
            //}


            if (enty.ContainsKey(property.Name))
            {
                var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                object value = null;

                if (propertyType == typeof(int?))
                {
                    int intValue;
                    if (int.TryParse(enty[property.Name], out intValue))
                    {
                        value = intValue;
                    }
                }
                else
                {
                    value = Convert.ChangeType(enty[property.Name], propertyType);
                }

                property.SetValue(obj, value);
            }


            Console.WriteLine($"{property.Name} : {property.GetValue(obj)}");


        }
        Console.WriteLine($"{obj}");
        return obj;
    }
    catch (Exception ex)
    {

        Console.WriteLine($"An error occurred: {ex.Message}");
        return null;
    }
}
public partial class Yuan
{
    [DisplayName("编号")]
    public int Id { get; set; }

    [DisplayName("姓名")]
    public string? Name { get; set; }

    [DisplayName("性别")]
    public string? Sex { get; set; }

    [DisplayName("年龄")]
    public int? Age { get; set; }

    [DisplayName("类型编号")]
    public int Typeid { get; set; }

    [DisplayName("价格")]
    public decimal? Price { get; set; }
}